import React, { useContext, useEffect, useState } from 'react'
import {PlaygroundContext} from '../PlaygroundContext'
import './fileItem.scss'
export default function FileNameList(){
    const {files,setSelectdFileName,addFile} = useContext(PlaygroundContext)
    const [tabs,setTabs] = useState([''])
    useEffect(()=>{
        setTabs(Object.keys(files))
    },[files])
    const handleClick = (v:string)=>{

        setSelectdFileName(v)
    }
    const handleDelete = (v:string,e:React.MouseEvent)=>{
        e.stopPropagation()
        
        delete files[v]
        setTabs(Object.keys(files))
    }
    const handlePlus = ()=>{
        addFile('new')
    }
    function FileNameItem(props:{filename:string}){
        const {filename=''} = props
        return <div onClick={()=>{handleClick(filename)}} className='item'>{filename}
        <span onClick={(e:React.MouseEvent)=>{handleDelete(filename,e)}}>x</span>
         </div>
    }
    return <div style={{display:'flex',width:'100%',overflowX:'auto'}}>
        {tabs.map(v=>{
            return <FileNameItem key={v} filename={v}></FileNameItem>
        })}
        <div className='plus' onClick={handlePlus}>+</div>
    </div>
}